/**
 * @api post control.
 *
 * User: yunshengzhu
 * Date: 2020/12/1
 * Time: 下午6:08
 */
package control

import (
	"card-platform/config"
	"card-platform/model"
	"encoding/json"
	"errors"
	"pkg/cfg"
	"time"
)

const (
	merchantStatusApply   = 0
	merchantStatusPass    = 1
	merchantStatusNotPass = 2
)

type Merchant struct {
}

// swagger:operation POST /merchantType 商户类 merchantTypeReq
// ---
// summary: 获取商户类型列表 merchantType.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/merchantTypeListResp"
func (a *Merchant) MerchantType(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	list, err := model.MerchantTypeAll()
	return list, config.OK, err
}

// swagger:operation POST /applyMerchant 商户类 applyMerchantReq
// ---
// summary: 申请成为商户applyMerchant.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/okResp"
func (a *Merchant) ApplyMerchant(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := ApplyMerchantReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}
	merchant, _ := model.GetMerchantUserId(userId)
	merchant.UserId = userId
	merchant.Name = req.Name
	merchant.BusinessLicense = req.BusinessLicense
	merchant.Phone = req.Phone
	merchant.Address = req.Address
	merchant.Lat = req.Lat
	merchant.Lon = req.Lon
	merchant.CreateTime = time.Now().Unix()
	merchant.Status = merchantStatusApply
	merchant.TypeId = req.TypeId
	merchant.Logo = req.Logo
	merchant.MName = req.MName
	merchant.Desc = req.Desc
	if merchant.Mid <= 0 {
		err = model.CreateMerchant(merchant)
	} else {
		err = model.UpdateMerchant(merchant)
	}
	if err != nil {
		return nil, config.ERR, err
	}
	return nil, config.OK, nil
}

// swagger:operation POST /getMerchant 商户类 getMerchantReq
// ---
// summary: 查看商户信息getMerchant.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/merchantResp"
func (a *Merchant) GetMerchant(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := GetMerchantReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	merchant := model.MerchantDb{}
	if req.Mid > 0 {
		merchant, err = model.GetMerchantMid(req.Mid)
	} else {
		merchant, err = model.GetMerchantUserId(userId)
	}
	if err != nil && err != model.ErrRecordNotFound {
		return nil, config.ERR, err
	}
	if merchant.Mid <= 0 {
		return nil, config.ERR, errors.New("商户信息不存在")
	}
	return merchant, config.OK, nil
}

// swagger:operation POST /merchantList 商户类 merchantListReq
// ---
// summary: 管理员获取商户列表merchantList.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/merchantListResp"
func (a *Merchant) MerchantList(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := MerchantListReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}
	count, err := model.GetMerchantCount(req.Status)
	if err != nil {
		cfg.LogErr("err:", err)
	}
	list, err := model.GetMerchantList(req.Status, req.Page, req.Size)
	if err != nil {
		cfg.LogErr("err:", err)
	}
	o := make(map[string]interface{})
	o["count"] = count
	o["list"] = list
	return o, config.OK, nil
}

// swagger:operation POST /auditMerchant 商户类 auditMerchantReq
// ---
// summary: 审核商户auditMerchant.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/okResp"
func (a *Merchant) AuditMerchant(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := AuditMerchantReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	user, err := model.GetUserId(userId)
	if err != nil {
		cfg.LogErr("err:", err)
	}

	if user.Platform != 1 {
		cfg.LogErr("当前用不具备审核权限:", user)
		return nil, config.ERR, errors.New("当前用户不具备审核权限")
	}
	merchant, err := model.GetMerchantMid(req.Mid)
	if err != nil && err != model.ErrRecordNotFound {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if merchant.Mid <= 0 {
		return nil, config.ERR, errors.New("商户不存在")
	}

	merchant.Status = req.Status
	merchant.Excuse = req.Excuse
	merchant.AuditTime = time.Now().Unix()
	err = model.UpdateMerchant(merchant)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if merchant.Status == merchantStatusPass {
		//设置用户类型为商户
		model.UpdateUserIdTye(merchant.UserId, UserTypMerchant)
	}
	return nil, config.OK, nil
}

// swagger:operation POST /nearbyMerchant 商户类 nearbyMerchantReq
// ---
// summary: 附近商家列表接口 /nearbyMerchant.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/merchantListResp"
func (a *Merchant) NearbyMerchant(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := NearbyMerchantReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}
	list, err := model.NearbyMerchantList(req.Lon, req.Lat, req.Page, req.Size, req.Order, req.TypeId)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}
	resp := make(map[string]interface{})
	resp["list"] = list
	resp["count"], err = model.GetMerchantTypeIdCount(1, req.TypeId)
	return resp, config.OK, err
}

// swagger:operation POST /getQrDetail 商户类 getQrDetailReq
// ---
// summary: 通过二维码获取商户详情 /getQrDetail.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/getQrDetailResp"
func (a *Merchant) GetQrDetail(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := GetQrDetailReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	order, err := model.GetOrderQrCode(req.QrCode)
	if err != nil && err != model.ErrRecordNotFound {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	merchant, err := model.GetMerchantUserId(userId)
	if err != nil && err != model.ErrRecordNotFound {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if merchant.Mid <= 0 {
		cfg.LogErr("err:", err)
		return nil, config.ERR, errors.New("无权限")
	}

	if order.Mid != merchant.Mid {
		cfg.LogErr("商户订单异常,非当前商户订单", order)
		return nil, config.ERR, errors.New("订单无权限")
	}

	if order.ExpQrTime < time.Now().Unix() {
		cfg.LogErr("二维码已过期", order)
		return nil, config.ERR, errors.New("二维码已过期")
	}

	if order.QrStatus == 1 {
		cfg.LogErr("二维码已核销:", order)
		return nil, config.ERR, errors.New("无效二维码")
	}

	order.ProList, _ = model.GetOrderDetailList(order.OrderNumber)
	order.Merchant, _ = model.GetMerchantMid(order.Mid)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}
	return order, config.OK, err
}

// swagger:operation POST /verifyQr 商户类 verifyQrReq
// ---
// summary: 核销二维码 /verifyQr.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/okResp"
func (a *Merchant) VerifyQr(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := VerifyQrReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	order, err := model.GetOrderQrCode(req.QrCode)
	if err != nil && err != model.ErrRecordNotFound {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	merchant, err := model.GetMerchantUserId(userId)

	if err != nil && err != model.ErrRecordNotFound {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if merchant.Mid <= 0 {
		cfg.LogErr("err:", err)
		return nil, config.ERR, errors.New("当前用户非商户")
	}

	if order.Mid != merchant.Mid {
		cfg.LogErr("商户订单异常,非当前商户订单", order)
		return nil, config.ERR, errors.New("商户订单不存在")
	}

	if order.ExpQrTime < time.Now().Unix() {
		cfg.LogErr("二维码已过期", order)
		return nil, config.ERR, errors.New("二维码已过期")
	}

	if order.QrStatus == 1 {
		cfg.LogErr("二维码已核销:", order)
		return nil, config.ERR, errors.New("无效二维码")
	}

	order.QrStatus = 1
	order.VerifyTime = time.Now().Unix()
	order.Status = 3
	err = model.UpdateOrderQr(order)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, errors.New("核销失败")
	}

	// 结算收益
	go model.RemitAmount(order.OrderNumber)

	return nil, config.OK, nil
}

// swagger:operation POST /merchantOrderList 商户类 merchantOrderListReq
// ---
// summary: 获取商户订单 /merchantOrderList.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/merchantOrderListResp"
func (a *Merchant) MerchantOrderList(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := MerchantOrderListReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}
	resp := MerchantOrderListResp{}
	merchant, err := model.GetMerchantUserId(userId)
	if err != nil {
		cfg.LogErr("err:", err)
		return resp, config.ERR, err
	}

	if merchant.Mid <= 0 {
		return resp, config.ERR, errors.New("当前用户非商户")
	}

	var typ int
	if req.Online == 0 {
		typ = 2
	}

	if req.Online == 1 {
		typ = 3
	}

	resp.Count, err = model.GetOrderMidCount(merchant.Mid, req.Status, req.Key, typ)
	resp.List, err = model.GetOrderMidList(merchant.Mid, req.Status, req.Key, typ, req.Page, req.Size)
	for idx, v := range resp.List {
		resp.List[idx].ProList = a.getUserOrderDetail(v.OrderNumber)
	}
	return resp, config.OK, nil
}

func (a *Merchant) getUserOrderDetail(orderNumber string) (list []model.OrderDetailDb) {
	list, err := model.GetOrderDetailList(orderNumber)
	if err != nil {
		cfg.LogErr("err:", err)
	}
	for idx, v := range list {
		temps := make([]string, 0)
		json.Unmarshal([]byte(v.Img), &temps)
		list[idx].Imgs = temps
	}
	return list
}

// swagger:operation POST /merchantOrderDetail 商户类 merchantOrderDetailReq
// ---
// summary: 获取商户订单详情 /merchantOrderDetail.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/merchantOrderDetailResp"
func (a *Merchant) MerchantOrderDetail(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := MerchantOrderDetailReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	merchant, err := model.GetMerchantUserId(userId)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if merchant.Mid <= 0 {
		return nil, config.ERR, errors.New("当前用户非商户")
	}

	order, err := model.GetOrderNumber(req.OrderNumber)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if order.Mid != merchant.Mid {
		return nil, config.ERR, errors.New("不存在的订单数据")
	}
	list := a.getUserOrderDetail(req.OrderNumber)
	return list, config.OK, err
}

// swagger:operation POST /deliverOrder 商户类 deliverOrderReq
// ---
// summary: 订单发货 /deliverOrder.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/okResp"
func (a *Merchant) DeliverOrder(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := DeliverOrderReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	merchant, err := model.GetMerchantUserId(userId)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if merchant.Mid <= 0 {
		return nil, config.ERR, errors.New("当前用户非商户")
	}

	order, err := model.GetOrderNumber(req.OrderNumber)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if order.Mid != merchant.Mid {
		return nil, config.ERR, errors.New("不存在的订单数据")
	}

	order.ExpressCompany = req.ExpressCompany
	order.WaybillNumber = req.WaybillNumber
	order.Status = 2
	err = model.UpdateOrder(order)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}
	return nil, config.OK, nil
}

// swagger:operation POST /editOrderPrice 商户类 editOrderPriceReq
// ---
// summary: 修改订单价格 /editOrderPrice.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/okResp"
func (a *Merchant) EditOrderPrice(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := EditOrderPriceReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	merchant, err := model.GetMerchantUserId(userId)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if merchant.Mid <= 0 {
		return nil, config.ERR, errors.New("当前用户非商户")
	}

	order, err := model.GetOrderNumber(req.OrderNumber)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if order.Mid != merchant.Mid {
		return nil, config.ERR, errors.New("不存在的订单数据")
	}

	wx := NewWeixinOrder()
	_, err = wx.CloseOrder(order.OrderNumber)
	if err != nil {
		cfg.LogErr("err:", err)
	}

	err = model.UpdateOrderPayAmount(req.OrderNumber, req.PayAmount)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}
	return nil, config.OK, nil
}
